//
//  WYHomeTableViewController.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/9.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit

import SVProgressHUD


//重用标记
private let HomeTableViewCellIdentifier = "HomeTableViewCellIdentifier"

class WYHomeTableViewController: WYVisitorUITableViewController {
    //懒加载 viewModel 对象
    private lazy var statusListViewModel: WYStatusListViewModel = WYStatusListViewModel()
    // MARK: -- 懒加载控件 菊花转 上拉刷新
    private lazy var pullUpView: UIActivityIndicatorView = {
    
       let indicatiorView = UIActivityIndicatorView()
        indicatiorView.color = UIColor.redColor()
        return indicatiorView
    }()
//    //使用系统的下拉刷新
//    private lazy var pulldownView: UIRefreshControl = {
//        
//        let ctr = UIRefreshControl()
//        //添加下拉刷新事件
//        ctr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
//        return ctr
//    }()
//    
    private lazy var pullDownView: WYRefreshControl = {
    
        let ctr = WYRefreshControl()
        //添加改变事件
        ctr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        return ctr
    }()
    //创建弹出界面  如果让我写的话就会添加 UIview 但是老师直接给一个 UIlabel t他正好继承自 UIview 节省了一步
    private lazy var tipLabel: UILabel = {
    
        let label = UILabel(textColor: UIColor.whiteColor(), fontSize: 13)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = .Center
        //默认情况下是隐藏的
        label.hidden = true
        return label
        
    }()
    
    var statusList: [WYStatus]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.redColor()
        
        //如果登陆
        if isLogin {
            //设置 tiplabel 的坐标 
            setUpUI()
            
            //设置 tableviewCell 相关
             stupUPtabView()
            //登陆
             loadStatus()
            
        }else{
        
            visitorView?.updateVisitorinfo(nil, imageName: nil)
        }
    }
    
    
    //设置控件约束
    private func setUpUI() {
        
        guard let nav = self.navigationController else {
        
            return
        }
        //界面添加在 navcontroller 后面
        nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
        tipLabel.frame = CGRect(x: 0, y: 67 - 30, width: nav.navigationBar.width, height: 30)
  
    }
    
    
    private func startAnimation(message: String) {
        
        //如果在执行动画 则不需要执行 通过是否显示这个 label可以知道是否在执行动画
        if tipLabel.hidden == false {
        
            return
        }
        
        //显示
        tipLabel.hidden = false
        tipLabel.text = message
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
        }
        
    }
    private func stupUPtabView() {
        
        //注册 cell
        tableView.registerClass(WYStatusTableViewCell.self, forCellReuseIdentifier: HomeTableViewCellIdentifier)
        //通过设置自动行高 设置高度
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估行高
        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = 200
        
        //MARK: -- 添加自定义下拉刷新
        tableView.addSubview(pullDownView)
        
        //MARK: -- 将菊花转添加为 footCell
        tableView.tableFooterView = pullUpView
        //指定大小
        pullUpView.sizeToFit()
        
     }
    
    
    //结束刷新
    private func endRefreshing() {
    //停止动画
        pullUpView.stopAnimating()
        //系统的下拉刷新
//       pulldownView.endRefreshing()÷
        pullDownView.endRefreshing()
        
        
        
    }
    //下拉刷新
    @objc private func pullDownRefresh() {
        
          loadStatus()
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
//        
//            //结束刷新
//            print("少年们让我加载数据")
////            self.pulldownView.endRefreshing()
//        }
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
//           
////            self.pulldownView.endRefreshing()
//        })
        
     
        
    }
    private func loadStatus() {
    
        statusListViewModel.loadStatus(pullUpView.isAnimating()) { (isSuccess, message) -> () in
            
            if !self.pullUpView.isAnimating() {
                
                //开启 tip 动画
                self.startAnimation(message)
                
                
            }
            //结束刷新
            self.endRefreshing()
            
            if isSuccess {
            
                self.tableView.reloadData()
            }
        }
    
    }

}

 
    
// MARK: - Table view data source

    
extension WYHomeTableViewController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        
        return statusListViewModel.statusList.count
        
//        return statusList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
      
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCellIdentifier, forIndexPath: indexPath) as? WYStatusTableViewCell
        
//            cell.textLabel?.text = statusList![indexPath.row].text
       let stausViewModel = statusListViewModel.statusList[indexPath.row]
        
        //设置需要的 viewModel
        cell?.statusViewModel = stausViewModel
        
        return cell!
    }
    //将要显示那个 cell
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        //判断是否是最后一个 cell
        if indexPath.row == statusListViewModel.statusList.count - 1 && !pullUpView.isAnimating() {
        
            //开启据换zhuan
            pullUpView.startAnimating()
            print("已经是最后一个cell数据了")
            loadStatus()
        }
    }
    
}











